using System;
using System.Security.Cryptography;
using Cmpp.Client.Cmpp3Message.Utility;

namespace Cmpp.Client.Cmpp3Message {
    internal class Cmpp3ConnectRequest : Cmpp3Request {
        private readonly byte[] m_authenticate;
        private readonly string m_spId;
        private readonly uint m_timestamp;
        private readonly byte m_version;

        public Cmpp3ConnectRequest(string spid, string password)
            : base(Cmpp3Command.ConnectRequest) {
            m_spId = spid;
            m_version = 48;
            m_timestamp = uint.Parse(DataConvert.GetTimeStampString(DateTime.Now));
            m_authenticate = CreateAuthenticate(m_spId, password);
        }

        public string SpId {
            get {
                return m_spId;
            }
        }

        public byte[] Authenticate {
            get {
                return m_authenticate;
            }
        }

        public byte Version {
            get {
                return m_version;
            }
        }

        public uint Timestamp {
            get {
                return m_timestamp;
            }
        }

        private static byte[] CreateAuthenticate(string spId, string password) {
            var writer = new CmppMessageWriter();
            var timeStamp = DataConvert.GetTimeStampString(DateTime.Now);

            writer.Write(spId);
            writer.Write(new byte[9]);
            writer.Write(password);
            writer.Write(timeStamp);

            byte[] byteBuffer = writer.ToBytes();

            byte[] byteAuth = new MD5CryptoServiceProvider().ComputeHash(byteBuffer, 0, byteBuffer.Length);

            return byteAuth;
        }

        protected override void WriteBody(CmppMessageWriter writer) {
            writer.Write(m_spId);
            writer.Write(m_authenticate);
            writer.Write(m_version);
            writer.Write(m_timestamp);
        }
    }
}